//
//  AppDelegate.m
//  SIPphone
//
//  Created by wrt on 13-10-25.
//  Copyright (c) 2013年 wrtsoft. All rights reserved.
//

#import "AppDelegate.h"
#import "DialViewController.h"
#import "MessageViewController.h"
#import "ContactsViewController.h"
#import "MoreViewController.h"
#import "TFHpple.h"
#import "ContactsDateBase.h"
#import "FriendRespondDateBase.h"
#import "PromptChatDateBase.h"
#import "HistoryDataBase.h"
#import "PostMessageDataBase.h"
#import "AlarmDataBase.h"
#import "PromptChatMessage.h"
#import "FriendRespondMessage.h"
#import "AlarmMessage.h"
#import "PostMessage.h"
#import "FirstLogViewController.h"


@implementation AppDelegate

#define MAINIP @"114.215.105.179"
#define MAiNPORT @"28060"
@synthesize tabBarVC = _tabBarVC, tempArray = _tempArray, connectivity;

static UIBackgroundTaskIdentifier sBackgroundTask;   //后台运行的句柄标识
static dispatch_block_t sExpirationHandler = nil;    //后台运行的
static int counter = 0;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application aunch.
    
//    locManager = [[CLLocationManager alloc]init];
//    locManager.delegate = self;

    
    //后台 判断支不支持多线程 以及设置了申请后台
    sBackgroundTask = UIBackgroundTaskInvalid;
    multitaskingSupported = [[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)] && [[UIDevice currentDevice] isMultitaskingSupported];
    sBackgroundTask = UIBackgroundTaskInvalid;
    sExpirationHandler = ^{
        [[UIApplication sharedApplication] endBackgroundTask:sBackgroundTask];
        sBackgroundTask = UIBackgroundTaskInvalid;
    };
    
    
    //增加标识，用于判断是否是第一次启动应用...
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
    }
    //若为第一次启动
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
    {
        //若存在视频和音频编码的文件就删除 因为更新版本后 旧版本可能用着以前的plist配置文件
        if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"videoCode.plist"]])
        {
            [[NSFileManager defaultManager] removeItemAtPath:[self dataFilePath:@"videoCode.plist"] error:nil];
        }
        if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"videoOrder.plist"]])
        {
            [[NSFileManager defaultManager] removeItemAtPath:[self dataFilePath:@"videoOrder.plist"] error:nil];
        }
        if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"audioCode.plist"]])
        {
            [[NSFileManager defaultManager] removeItemAtPath:[self dataFilePath:@"audioCode.plist"] error:nil];
        }
        if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"audioOrder.plist"]])
        {
            [[NSFileManager defaultManager] removeItemAtPath:[self dataFilePath:@"audioOrder.plist"] error:nil];
        }
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
    }
    
    //实例NSUserDefaults
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    //设置程序第一次启动的数据
    self.isFristOpen = 1;

    //纪录程序启动的次数
    int i = [defaults integerForKey:@"RECORDOPENNUMBER"];
    if (i == 0)
    {
        self.isRecodeOpenNumber = 1;
        [defaults setInteger:self.isRecodeOpenNumber forKey:@"RECORDOPENNUMBER"];
        [defaults synchronize];
    }
    else
    {
        self.isRecodeOpenNumber = [defaults integerForKey:@"RECORDOPENNUMBER"];
        self.isRecodeOpenNumber = self.isRecodeOpenNumber + 1;
        [defaults setInteger:self.isRecodeOpenNumber forKey:@"RECORDOPENNUMBER"];
        [defaults synchronize];
    }
    
    //设置一个能判断网络的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    
    //设置判断网络是否连接的通知
    self.internetReachability = [Reachability reachabilityForInternetConnection];
	[self.internetReachability startNotifier];
	[self updateInterfaceWithReachability:self.internetReachability];
    
    
    //创建tabbar中的所有界面
    self.tabBarVC = [[UITabBarController alloc] init];
    
    //拨号界面创建
    DialViewController *dialVC = [[DialViewController alloc] initWithNibName:@"DialViewController" bundle:nil];
    UINavigationController *navForDial = [[UINavigationController alloc] initWithRootViewController:dialVC];
    navForDial.tabBarItem.title = NSLocalizedString(@"dial", @" 拨号 tabbar Item For dial name ");
    //设置tabbarItem的背景图
    [navForDial.tabBarItem setImage:[UIImage imageNamed:@"calltabbar.png"]];
    [navForDial.tabBarItem setSelectedImage:[UIImage imageNamed:@"calltabbar_h.png"]];
    
    
    
    //信息界面创建
    MessageViewController *msgVC = [[MessageViewController alloc] initWithNibName:@"MessageViewController" bundle:nil];
    self.navForMsg = [[UINavigationController alloc] initWithRootViewController:msgVC];
    self.navForMsg.tabBarItem.title = NSLocalizedString(@"message", @" 信息 tabbar Item For message name ");
    
    
    //设置tabbarItem的背景图
    [self.navForMsg.tabBarItem setImage:[UIImage imageNamed:@"message.png"]];
    [self.navForMsg.tabBarItem setSelectedImage:[UIImage imageNamed:@"message_h.png"]];
    
    
    //联系人界面创建
    ContactsViewController *contactVC = [[ContactsViewController alloc] initWithNibName:@"ContactsViewController" bundle:nil];
    UINavigationController *navForContact = [[UINavigationController alloc] initWithRootViewController:contactVC];
    navForContact.tabBarItem.title = NSLocalizedString(@"contact", @" 联系人 tabbar Item For contact name ");
    //设置tabbarItem的背景图
    [navForContact.tabBarItem setImage:[UIImage imageNamed:@"person.png"]];
    [navForContact.tabBarItem setSelectedImage:[UIImage imageNamed:@"person_h.png"]];
    
    
    //更多界面创建
    MoreViewController *moreVC = [[MoreViewController alloc] initWithNibName:@"MoreViewController" bundle:nil];
    UINavigationController *navForMore = [[UINavigationController alloc] initWithRootViewController:moreVC];
    navForMore.tabBarItem.title =  NSLocalizedString(@"more", @" 更多 tabbar Item For more name ");
    //设置tabbarItem的背景图
    [navForMore.tabBarItem setImage:[UIImage imageNamed:@"settings.png"]];
    [navForMore.tabBarItem setSelectedImage:[UIImage imageNamed:@"settings_h.png"]];

    //将4个界面放入tabbar中
    [self.tabBarVC setViewControllers:[NSArray arrayWithObjects:navForDial, self.navForMsg, navForContact, navForMore, nil]];
    self.tabBarVC.delegate = self;
    
    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    //判断版本号 然后选择相应的ui界面
    if (systemVersion >= 7.0)
    {
        self.tabBarVC.tabBar.tintColor = [UIColor colorWithRed:83/255.0 green:215/255.0 blue:105/255.0 alpha:1.0];
    }
    
    //程序开始时对SIP的一些相关设置读取并设置
    [self reloadSipSetting];
    
    //读取出当前用户名
    NSString *userName = [[NSString alloc] init];
    userName = [defaults valueForKey:@"SAVEUSERNAME"];
    //创建用于存储联系人的数据库
    ContactsDateBase *contactsDb = [ContactsDateBase shareContactsDataBase];
    [contactsDb changeTableName:userName];
    [contactsDb creatDB];
    [contactsDb readDB];
    
    //创建用于存储好友信息的数据库
    FriendRespondDateBase *friendRespondDB = [FriendRespondDateBase shareFriendRespondDateBase];
    [friendRespondDB changeTableName:userName];
    [friendRespondDB creatDB];
    [friendRespondDB readDB];
    
    //创建用于即时聊天的数据库
    PromptChatDateBase *promptDB = [PromptChatDateBase sharePromptChatDB];
    [promptDB changeTableName:userName];
    [promptDB creatDB];
    [promptDB readDB];
    
    //创建用于历史记录的数据库
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    [historyDB changeTableName:userName];
    [historyDB createDb];
    [historyDB loadArray:0];
    
    //创建用于推送消息的数据库
    PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
    [postMsgDB changeTableName:userName];
    [postMsgDB createDb];
    [postMsgDB loadArray];
    
    //创建用于报警信息的数据库
    AlarmDataBase *alarmDB = [AlarmDataBase shareAlarmDataBase];
    [alarmDB changeTableName:userName];
    [alarmDB creatDB];
    [alarmDB readDB];
    
    //接收推送消息 10秒循环跑获取xml的方法
    if (self.postTimer == nil)
    {
        self.postTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(readPostMessage) userInfo:nil repeats:YES];
    }
    
    //设置一个能接听的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callincoming) name:@"INCOMINGCALL" object:nil];
    
    //设置一个能通知－好友请求
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTabBarHaveNew:) name:@"FRIENDREQUSTFORTABBAR" object:nil];
    
    //设置一个能通知－即时聊天
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTabBarHaveChat:) name:@"PROMPTCHATTABBAR" object:nil];
    
    //设置一个能通知－报警信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTabBarHaveAlarm:) name:@"ALARMTABBAR" object:nil];
    
    
    //界面代码设置
    [self customizeApperance];
    
    FirstLogViewController *firstVC = [[FirstLogViewController alloc] init];
    
    NSString *first = [[NSString alloc] init];
    first = [defaults objectForKey:@"FRISTLOGSUCCESS"];

    BOOL isAoTuRegist = [defaults boolForKey:@"ISAUTOREGISTERSTATUS"];
    
    //根据是否是在首次登录界面成功登录来进入对应的首界面
    if (first.length > 0 && isAoTuRegist == YES)
    {
        self.window.rootViewController = self.tabBarVC;
        [defaults setBool:NO forKey:@"ISFIRSTLOGBEGIN"];
    }
    else
    {
        self.window.rootViewController = firstVC;
        [defaults setBool:YES forKey:@"ISFIRSTLOGBEGIN"];
    }
    [defaults synchronize];
    
    //设置tabbar为根视图
//    self.window.rootViewController = firstVC;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //启动图渐变效果
    UIImageView *splashScreen = [[UIImageView alloc] initWithFrame:self.window.bounds] ;
    if (([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)) {
        splashScreen.image = [UIImage imageNamed:@"Default-568h"];
    }else{
        splashScreen.image = [UIImage imageNamed:@"Default"];
    }
    
    [self.window addSubview:splashScreen];
    
    [UIView animateWithDuration:1.5 animations:^{
        CATransform3D transform = CATransform3DMakeScale(1.5, 1.5, 1.0);
        splashScreen.layer.transform = transform;
        splashScreen.alpha = 0.0;
    } completion:^(BOOL finished) {
        [splashScreen removeFromSuperview];
    }];
    
    return YES;
}

//- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
//{
//    SIPInterface *interface = [SIPInterface shareSIPInterface];
//    [interface enterBackground];
//    //20毫秒调用一次 掉四十次
//    for (int i = 0; i < 400; i++)
//    {
//        [interface iterator];
//        usleep(20000);
//    }
//}

- (void)applicationWillResignActive:(UIApplication *)application
{
    //当准备进入后台或者有通知消息弹出时调用。
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    //当进入后台时调用
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[SIPInterface shareSIPInterface] hang_call];
    [[SIPInterface shareSIPInterface] hang_incoming];
    
//    BOOL backgroundAccpeted = [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{
//        SIPInterface *interface = [SIPInterface shareSIPInterface];
//        [interface enterBackground];
////        [interface iterator];
//    }];
//    
//    
//    
//    if (backgroundAccpeted)
//    {
//        NSLog(@"后台成功");
//    }
//    else
//    {
//        NSLog(@"丢失连接");
//    }
//    
//    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{}];
    
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
    if (self->multitaskingSupported) {
        
            sBackgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:sExpirationHandler];
        
            BOOL backgroundAccpeted = [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{
                
//                 if (connectivity==none)
//                {
//                    //don't trust ios when he says there is no network. Create a new reachability context, the previous one might be mis-functionning.
//                    [self setupNetworkReachabilityCallback];
//                }
                
                SIPInterface *interface = [SIPInterface shareSIPInterface];
                [interface enterBackground];
                //20毫秒调用一次 掉四十次
                for (int i = 0; i < 400; i++)
                {
                    [interface iterator];
                    usleep(20000);
                }
                
                NSLog(@"background task start time %lld.",(long long)[[UIApplication  sharedApplication] backgroundTimeRemaining]);
                
            }];
        
        
        if (backgroundAccpeted)
        {
            NSLog(@"后台成功");
            
//            [locManager startMonitoringSignificantLocationChanges];
            
//            SIPInterface *interface = [SIPInterface shareSIPInterface];
//            [interface setWindownId:nil];
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:@"yes" forKey:@"ISLIVEINBACKGROUND"];
            [defaults synchronize];
            
            
            SIPInterface *interface = [SIPInterface shareSIPInterface];
            [interface enterBackground];
            //20毫秒调用一次 掉四十次
            for (int i = 0; i < 40; i++)
            {
                [interface iterator];
                usleep(20000);
            }
        }
        else
        {
            NSLog(@"丢失连接");
        }
    }
#endif
    
    
    
    
//    [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{}];
        //让程序在后台一直运行
//        UIApplication *app = [UIApplication sharedApplication];
//        __block    UIBackgroundTaskIdentifier bgTask;
//        bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [app endBackgroundTask:bgTask];
//                bgTask = UIBackgroundTaskInvalid;
//            });
//        }];
    
    //切换UDP和TCP
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *tempUdpOrTcp = [[NSString alloc] init];
        tempUdpOrTcp = [defaults objectForKey:@"SAVEVIDEOTRANSPORT"];
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        if (tempUdpOrTcp.length > 0)
        {
            if ([tempUdpOrTcp isEqualToString:@"UDP"])
            {
                [interface setVideotransport:2];
            }
        }
        else
        {
            [interface setVideotransport:2];
        }
    });
    
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (bgTask != UIBackgroundTaskInvalid)
//                {
//                    bgTask = UIBackgroundTaskInvalid;
//                }
//            });
//        });
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    //程序将进入前台时调用
//    [[UIApplication sharedApplication] clearKeepAliveTimeout];
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
    if (sBackgroundTask != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:sBackgroundTask];
        sBackgroundTask = UIBackgroundTaskInvalid;
    }
//    [interface enterBackground];

#endif
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *tempUdpOrTcp = [[NSString alloc] init];
    tempUdpOrTcp = [defaults objectForKey:@"SAVEVIDEOTRANSPORT"];
    NSString *tempIsInCallState = [[NSString alloc] init];
    tempIsInCallState = [defaults objectForKey:@"ISINCALLSTATENOW"];
//
    
    //切换UDP和TCP
    if (tempUdpOrTcp.length > 0)
    {
        if ([tempUdpOrTcp isEqualToString:@"UDP"] && [tempIsInCallState isEqualToString:@"NO"])
        {
            [interface setVideotransport:1];
        }
        if ([tempUdpOrTcp isEqualToString:@"UDP"] && [tempIsInCallState isEqualToString:@"YES"])
        {
            [defaults setObject:@"YES" forKey:@"ISBACKGROUNDINCALL"];
        }
    }
    else
    {
        [interface setVideotransport:1];
    }
    
    [defaults setObject:@"no" forKey:@"ISLIVEINBACKGROUND"];
    [defaults synchronize];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    
//    [locManager stopMonitoringSignificantLocationChanges];
//    [locManager startUpdatingLocation];
    //程序唤醒时调用
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface enterBackground];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    //点通知进来之后的处理方法
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    //程序在后台情况下终止时调用
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[SIPInterface shareSIPInterface] setMyStatusWithInt:0];
    [[SIPInterface shareSIPInterface] hang_call];
    [[SIPInterface shareSIPInterface] hang_incoming];
}

#pragma mark - 
#pragma mark UIsetting
- (void)customizeApperance
{
    //竖屏
    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    //判断版本号 然后选择相应的ui界面
    if (systemVersion >= 7.0)
    {
        UIImage *image44 = [[UIImage imageNamed:@"导航栏for7.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [[UINavigationBar appearance] setBackgroundImage:image44 forBarMetrics:UIBarMetricsDefault];
        [UINavigationBar appearance].tintColor = [UIColor colorWithRed:83/255.0 green:215/255.0 blue:105/255.0 alpha:1.0];
        
        //设置导航栏字体样式
        [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor],UITextAttributeTextColor,[UIFont fontWithName:@"STHeitiSC-Medium" size:0.0],UITextAttributeFont, nil]];
        
        
        
    }
    else
    {
        UIImage *image44 = [[UIImage imageNamed:@"导航栏for6.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [[UINavigationBar appearance] setBackgroundImage:image44 forBarMetrics:UIBarMetricsDefault];
        
        [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor grayColor],UITextAttributeTextColor,[UIFont fontWithName:@"Heiti SC" size:0.0],UITextAttributeFont, nil] forState:UIControlStateNormal];
        [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:83/255.0 green:215/255.0 blue:105/255.0 alpha:1.0],UITextAttributeTextColor,[UIFont fontWithName:@"Heiti SC" size:0.0],UITextAttributeFont, nil] forState:UIControlStateSelected];
        

        //设置按钮样式
        UIImage *button30 = [[UIImage imageNamed:@"button_textured_30"]
                             resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 5)];
        [[UIBarButtonItem appearance] setBackgroundImage:button30 forState:UIControlStateNormal
                                              barMetrics:UIBarMetricsDefault];

        
        //设置导航栏返回按钮样式
        UIImage *buttonBack30 = [[UIImage imageNamed:@"button_back_textured_30"]
                                 resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 5)];
        [[UIBarButtonItem appearance] setBackButtonBackgroundImage:buttonBack30
                                                          forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        
        //设置导航栏按钮字体样式
        [[UIBarButtonItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:83/255.0 green:215/255.0 blue:105/255.0 alpha:1.0],UITextAttributeTextColor ,[NSValue valueWithCGSize:CGSizeMake(0.0, 0.0)] , UITextAttributeTextShadowOffset ,[UIColor clearColor] ,UITextAttributeTextShadowColor , nil] forState:UIControlStateNormal];
        
        //设置导航栏按钮字体样式
        [[UIBarButtonItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:83/255.0 green:215/255.0 blue:105/255.0 alpha:1.0],UITextAttributeTextColor ,[NSValue valueWithCGSize:CGSizeMake(0.0, 0.0)] , UITextAttributeTextShadowOffset ,[UIColor clearColor] ,UITextAttributeTextShadowColor , nil] forState:UIControlStateReserved];
        
        //设置导航栏按钮字体样式
        [[UIBarButtonItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:83/255.0 green:215/255.0 blue:105/255.0 alpha:1.0],UITextAttributeTextColor ,[NSValue valueWithCGSize:CGSizeMake(0.0, 0.0)] , UITextAttributeTextShadowOffset ,[UIColor clearColor] ,UITextAttributeTextShadowColor , nil] forState:UIControlStateApplication];
        
        //设置导航栏按钮按下字体样式
        [[UIBarButtonItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor ,[NSValue valueWithCGSize:CGSizeMake(0.0, 0.0)] , UITextAttributeTextShadowOffset ,[UIColor clearColor] ,UITextAttributeTextShadowColor , nil] forState:UIControlStateHighlighted];
        
        [[UITabBar appearance] setSelectionIndicatorImage:[UIImage imageNamed:@"工具栏选择背景.png"]];
        
        
        //设置导航栏字体样式
        [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
         [UIFont boldSystemFontOfSize:20],UITextAttributeFont,
         [UIColor blackColor],UITextAttributeTextColor ,
         [NSValue valueWithCGSize:CGSizeMake(0.0, 0.0)] , UITextAttributeTextShadowOffset ,
         [UIColor whiteColor] ,UITextAttributeTextShadowColor ,
         nil]];
    }
    
    //设置toolbar的样式
    UIImage *toolbarBackground = [[UIImage imageNamed:@"导航栏for6.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [[UIToolbar appearance] setBackgroundImage:toolbarBackground forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
    //设置Tab的样式
    UIImage *tabBackground = [[UIImage imageNamed:@"工具栏.png"]
                              resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [[UITabBar appearance] setBackgroundImage:tabBackground];
    
}

#pragma mark -
#pragma mark SIPsettingMethod
//读取SIP的相关设置
- (void)reloadSipSetting
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    
    //=============================
    //保存默认的IP地址和端口
    [defaults setObject:MAINIP forKey:@"SAVEIPADDRESS"];
    [defaults setObject:MAiNPORT forKey:@"SAVEPORT"];
    
    //=============================
    //SIP初始化  设置回调
    //单例化SIP并设置回调
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface startSip];
    [interface my_callerback];
    
    //ios网络标示不可信 所以监听网络
    [self setupNetworkReachabilityCallback];
    //启动定时器20毫秒一次
//    [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(timerForIterator) userInfo:nil repeats:YES];
    
    //设置设备信息和版本号
    NSString *tempDeviceName = [[NSString alloc] init];
    if ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) == YES)
    {
        tempDeviceName = @"WRTSIP-IOS-PAD-";
    }
    else
    {
        tempDeviceName = @"WRTSIP-IOS-PHONE-";
    }
    [interface setDeviceName:tempDeviceName andVersionNumber:@"V1.2"];
    
    
    //视频是否打开
    NSString *isOpenVideo = [[NSString alloc] init];
    isOpenVideo = [defaults objectForKey:@"SAVEISOPENVIDEO"];
    if (isOpenVideo.length > 0)
    {
        if ([isOpenVideo isEqualToString:@"YES"])
        {
            [interface isOpenVideo:YES];
        }
        else if ([isOpenVideo isEqualToString:@"NO"])
        {
            [interface isOpenVideo:NO];
        }
    }
    //==============================
    //视频配置
    //预览视频是否打开
    NSString *isOpenSelfVideo = [[NSString alloc] init];
    isOpenSelfVideo = [defaults objectForKey:@"SAVEISOPENSELFVIDEO"];
    if (isOpenSelfVideo.length > 0)
    {
        if ([isOpenSelfVideo isEqualToString:@"YES"])
        {
            [interface isOpenSelfVideo:YES];
        }
        else if ([isOpenSelfVideo isEqualToString:@"NO"])
        {
            [interface isOpenSelfVideo:NO];
        }
    }
    //是否用前置摄像头
    NSString *isUseFrontCamera = [[NSString alloc] init];
    isUseFrontCamera = [defaults objectForKey:@"SAVEFRONTCAMERA"];
    if (isUseFrontCamera.length > 0)
    {
        if ([isUseFrontCamera isEqualToString:@"YES"])
        {
            [interface FonrtDevice:1];
        }
        else if ([isUseFrontCamera isEqualToString:@"NO"])
        {
            [interface FonrtDevice:0];
        }
    }
    else
    {
        [interface FonrtDevice:1];
    }
    //视频的格式
    NSString *tempSegmented = [[NSString alloc] init];
    tempSegmented = [defaults objectForKey:@"SAVEVIDEOSIZE"];
    if (tempSegmented.length > 0)
    {
        if ([tempSegmented isEqualToString:@"QCIF"])
        {
            [interface videoSize:@"QCIF"];
        }
        else if ([tempSegmented isEqualToString:@"CIF"])
        {
            [interface videoSize:@"CIF"];
        }
        else if ([tempSegmented isEqualToString:@"VGA"])
        {
            [interface videoSize:@"VGA"];
        }
    }
    
    
    
    //视频编解码相关
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"videoCode.plist"]] && [[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"videoOrder.plist"]])
    {
        NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithContentsOfFile:[self dataFilePath:@"videoCode.plist"]];
        NSMutableArray *videoCodeArray = [[NSMutableArray alloc] init];
        NSMutableArray *codeNumberArray = [[NSMutableArray alloc] init];
        int videoCodeCount = [interface getVideoCodeCount];
        for (int i = 0; i < videoCodeCount; i++)
        {
            unsigned long videoCodeNumber = [interface getVideocodeNumber:i];
            NSString *tempVideoCodeName = [interface getAudioAndVideoName:videoCodeNumber];
            [videoCodeArray addObject:tempVideoCodeName];
            [codeNumberArray addObject:[NSNumber numberWithUnsignedLong:videoCodeNumber]];
        }
        
        //首先先设置开关
        for (int i = 0 ; i < videoCodeArray.count ; i++)
        {
            NSNumber *onOroff = [tempDic objectForKey:videoCodeArray[i]];
            if ([onOroff intValue] == 0)
            {
                [interface setEnabledAudioAndVideo:[codeNumberArray[i] unsignedLongValue] andOn:0];
            }
        }
        
        
        //再设置优先级 各种比较循环的算法
        NSArray *tempVideoCodeArray = [[NSArray alloc] initWithContentsOfFile:[self dataFilePath:@"videoOrder.plist"]];
        for (int i = 0; i < tempVideoCodeArray.count; i++)
        {
            [videoCodeArray removeAllObjects];
            [codeNumberArray removeAllObjects];
            
            for (int l = 0; l < videoCodeCount; l++)
            {
                unsigned long videoCodeNumber = [interface getVideocodeNumber:l];
                NSString *tempVideoCodeName = [interface getAudioAndVideoName:videoCodeNumber];
                [videoCodeArray addObject:tempVideoCodeName];
                [codeNumberArray addObject:[NSNumber numberWithUnsignedLong:videoCodeNumber]];
            }
            
            for (int j = i; j < videoCodeArray.count; j++)
            {
                if ([tempVideoCodeArray[i] isEqualToString:videoCodeArray[j]])
                {
                    int dirMoveNumber = j - i;
                    if (dirMoveNumber != 0)
                    {
                        
                        [interface setAudioAndVideoMove:[codeNumberArray[j] unsignedLongValue] andDir:dirMoveNumber];
                        
                    }
                }
            }
        }
    }
    else if ((![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"videoCode.plist"]]) && (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"videoOrder.plist"]]))
    {
        //如果不存在那就创建并打开默认设置，然后再发到地层去。
        int videoCodeCount;
        unsigned long videoCodeNumber;
        NSMutableArray *videoCodeArray = [[NSMutableArray alloc] init];
        NSMutableArray *codeNumberArray = [[NSMutableArray alloc] init];
        NSMutableDictionary *videoCodeDic = [[NSMutableDictionary alloc] init];
        videoCodeCount = [interface getVideoCodeCount];
        for (int i = 0; i < videoCodeCount; i++)
        {
            videoCodeNumber = [interface getVideocodeNumber:i];
            NSString *tempVideoCodeName = [interface getAudioAndVideoName:videoCodeNumber];
            [videoCodeArray addObject:tempVideoCodeName];
            [codeNumberArray addObject:[NSNumber numberWithUnsignedLong:videoCodeNumber]];
        }
        
        NSMutableArray *tempYesOrNoArray = [[NSMutableArray alloc] init];
        for (int i = 0 ; i < videoCodeCount; i++)
        {
            if ([videoCodeArray[i] isEqualToString:@"H264"])
            {
                [tempYesOrNoArray addObject:[NSNumber numberWithInt:1]];
            }
            else
            {
                [tempYesOrNoArray addObject:[NSNumber numberWithInt:0]];
            }
        }
        
        videoCodeDic = [[NSMutableDictionary alloc] initWithObjects:tempYesOrNoArray forKeys:videoCodeArray];
        
        [videoCodeDic writeToFile:[self dataFilePath:@"videoCode.plist"] atomically:YES];
        
        [videoCodeArray writeToFile:[self dataFilePath:@"videoOrder.plist"] atomically:YES];
        
        
        //然后设置开关
        for (int i = 0 ; i < videoCodeArray.count ; i++)
        {
            NSNumber *onOroff = [videoCodeDic objectForKey:videoCodeArray[i]];
            if ([onOroff intValue] == 0)
            {
                [interface setEnabledAudioAndVideo:[codeNumberArray[i] unsignedLongValue] andOn:0];
            }
        }
    }
    
    
    
    
    
    






    //=================================
    //音频配置
    //是否打开音频
    NSString *isOpenSound = [[NSString alloc] init];
    isOpenSound = [defaults objectForKey:@"SAVEISOPENSOUND"];
    if (isOpenSound.length > 0)
    {
        if ([isOpenSound isEqualToString:@"YES"])
        {
            [interface isOpenSound:YES];
        }
        else if ([isOpenSound isEqualToString:@"NO"])
        {
            [interface isOpenSound:NO];
        }
    }
    
    
    //音频编解码相关
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"audioCode.plist"]] && [[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"audioOrder.plist"]])
    {
        NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] initWithContentsOfFile:[self dataFilePath:@"audioCode.plist"]];
        NSMutableArray *audioCodeArray = [[NSMutableArray alloc] init];
        NSMutableArray *codeNumberArray = [[NSMutableArray alloc] init];
        int audioCodeCount = [interface getAudioCodeCount];
        for (int i = 0; i < audioCodeCount; i++)
        {
            unsigned long audioCodeNumber = [interface getAudioCodeNumber:i];
            NSString *tempAudioCodeName = [interface getAudioAndVideoName:audioCodeNumber];
            [audioCodeArray addObject:tempAudioCodeName];
            [codeNumberArray addObject:[NSNumber numberWithUnsignedLong:audioCodeNumber]];
        }
        
        //首先先设置开关
        for (int i = 0 ; i < audioCodeArray.count ; i++)
        {
            NSNumber *onOroff = [tempDic objectForKey:audioCodeArray[i]];
            if ([onOroff intValue] == 0)
            {
                [interface setEnabledAudioAndVideo:[codeNumberArray[i] unsignedLongValue] andOn:0];
            }
        }
        
        
        //再设置优先级 各种比较循环的算法
        NSArray *tempAudioCodeArray = [[NSArray alloc] initWithContentsOfFile:[self dataFilePath:@"audioOrder.plist"]];
        for (int i = 0; i < tempAudioCodeArray.count; i++)
        {
            [audioCodeArray removeAllObjects];
            [codeNumberArray removeAllObjects];
            
            for (int l = 0; l < audioCodeCount; l++)
            {
                unsigned long audioCodeNumber = [interface getAudioCodeNumber:l];
                NSString *tempAudioCodeName = [interface getAudioAndVideoName:audioCodeNumber];
                [audioCodeArray addObject:tempAudioCodeName];
                [codeNumberArray addObject:[NSNumber numberWithUnsignedLong:audioCodeNumber]];
            }
            
            for (int j = i; j < audioCodeArray.count; j++)
            {
                if ([tempAudioCodeArray[i] isEqualToString:audioCodeArray[j]])
                {
                    int dirMoveNumber = j - i;
                    if (dirMoveNumber != 0)
                    {
                        
                        [interface setAudioAndVideoMove:[codeNumberArray[j] unsignedLongValue] andDir:dirMoveNumber];
                        
                    }
                }
            }
        }
    }
    else if ((![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"audioCode.plist"]]) && (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath:@"audioOrder.plist"]]))
    {
        int audioCodeCount;
        unsigned long audioCodeNumber;
        NSMutableArray *audioCodeArray = [[NSMutableArray alloc] init];
        NSMutableArray *codeNumberArray = [[NSMutableArray alloc] init];
        NSMutableDictionary *audioCodeDic = [[NSMutableDictionary alloc] init];
        
        audioCodeCount = [interface getAudioCodeCount];
        for (int i = 0; i < audioCodeCount; i++)
        {
            audioCodeNumber = [interface getAudioCodeNumber:i];
            NSString *tempAudioCodeName = [interface getAudioAndVideoName:audioCodeNumber];
            [audioCodeArray addObject:tempAudioCodeName];
            [codeNumberArray addObject:[NSNumber numberWithUnsignedLong:audioCodeNumber]];
        }

            NSMutableArray *tempYesOrNoArray = [[NSMutableArray alloc] init];
            for (int i = 0 ; i < audioCodeCount; i++)
            {
                if ([audioCodeArray[i] isEqualToString:@"G729/8000/1"] || [audioCodeArray[i] isEqualToString:@"PCMA/8000/1"] ||[audioCodeArray[i] isEqualToString:@"PCMU/8000/1"])
                {
                    [tempYesOrNoArray addObject:[NSNumber numberWithInt:1]];
                }
                else
                {
                    [tempYesOrNoArray addObject:[NSNumber numberWithInt:0]];
                }
            }
            
            audioCodeDic = [[NSMutableDictionary alloc] initWithObjects:tempYesOrNoArray forKeys:audioCodeArray];
            
            [audioCodeDic writeToFile:[self dataFilePath:@"audioCode.plist"] atomically:YES];
            [audioCodeArray writeToFile:[self dataFilePath:@"audioOrder.plist"] atomically:YES];
        
        //然后设置开关
        for (int i = 0 ; i < audioCodeArray.count ; i++)
        {
            NSNumber *onOroff = [audioCodeDic objectForKey:audioCodeArray[i]];
            if ([onOroff intValue] == 0)
            {
                [interface setEnabledAudioAndVideo:[codeNumberArray[i] unsignedLongValue] andOn:0];
            }
        }
        
        
        
    }
    
    
    //==================================
    //网络配置
    //SIP视频传输协议
    NSString *tempSegment = [[NSString alloc] init];
    tempSegment = [defaults objectForKey:@"SAVEVIDEOTRANSPORT"];
    if (tempSegment.length > 0)
    {
        if ([tempSegment isEqualToString:@"UDP"])
        {
            [interface setVideotransport:1];
        }
        else if ([tempSegment isEqualToString:@"TCP"])
        {
            [interface setVideotransport:2];
        }
    }
    else
    {
        //默认用TCP
        [interface setVideotransport:2];
        [defaults setObject:@"TCP" forKey:@"SAVEVIDEOTRANSPORT"];
    }
    
    //stun服务器
    NSString *tempstunServer = [[NSString alloc] init];
    tempstunServer = [defaults valueForKey:@"SAVESTUNSERVER"];
    if (tempstunServer.length > 0)
    {
        [interface setStunServer:tempstunServer];
    }
    else
    {
        [interface setStunServer:@"stun.3cx.com"];
        [defaults setObject:@"stun.3cx.com" forKey:@"SAVESTUNSERVER"];
    }
    
    //SIP协议使用端口
    NSString *tempSipPort = [[NSString alloc] init];
    tempSipPort = [defaults valueForKey:@"SAVESIPPORT"];
    if (tempSipPort.length > 0)
    {
        [interface setSIPport:tempSipPort];
    }
    
    //视频RTP端口
    NSString *tempVideoRTP = [[NSString alloc] init];
    tempVideoRTP = [defaults valueForKey:@"SAVERTPVIDEOPORT"];
    if (tempVideoRTP.length > 0)
    {
        [interface setRTPvideoPort:tempVideoRTP];
    }
    else
    {
        [interface setRTPvideoPort:@"0"];
    }
    
    //音频RTP端口
    NSString *tempSoundRTP = [[NSString alloc] init];
    tempSoundRTP = [defaults valueForKey:@"SAVERTPSOUNDPORT"];
    if (tempSoundRTP.length > 0)
    {
        [interface setRTPsoundPort:tempSoundRTP];
    }
    else
    {
        [interface setRTPsoundPort:@"0"];
    }
    
    //音视频上传带宽
    NSString *tempSoundAndVideoUp = [[NSString alloc] init];
    tempSoundAndVideoUp = [defaults valueForKey:@"SAVESOUNDANDVIDEOUPWIDTH"];
    if (tempSoundAndVideoUp.length > 0)
    {
        [interface setSoundAndVideoUpWidth:tempSoundAndVideoUp];
    }
    else
    {
        [interface setSoundAndVideoUpWidth:@"512"];
        [defaults setObject:@"512" forKey:@"SAVESOUNDANDVIDEOUPWIDTH"];
    }
    
    //音视频下载带宽
    NSString *tempSoundAndVideoDown = [[NSString alloc] init];
    tempSoundAndVideoDown = [defaults valueForKey:@"SAVESOUNDANDVIDEODOWNWIDTH"];
    if (tempSoundAndVideoDown.length > 0)
    {
        [interface setSoundAndVideoDownWidth:tempSoundAndVideoDown];
    }
    else
    {
        [interface setSoundAndVideoDownWidth:@"1024"];
        [defaults setObject:@"1024" forKey:@"SAVESOUNDANDVIDEODOWNWIDTH"];
    }
    
    //==================================
    //日志配置
    //是否打开日志
    NSString *isOpenNote = [[NSString alloc] init];
    isOpenNote = [defaults objectForKey:@"SAVEISOPENNOTE"];
    if (isOpenNote.length > 0)
    {
        if ([isOpenNote isEqualToString:@"YES"])
        {
            [interface isOpenNote:YES];
        }
        else if ([isOpenNote isEqualToString:@"NO"])
        {
            [interface isOpenNote:NO];
        }
    }
    //==================================
    //留言配置
    //是否打开留言
    NSString *isOpenMsg = [[NSString alloc] init];
    isOpenMsg = [defaults objectForKey:@"SAVEISOPENMESSAGE"];
    if (isOpenMsg.length > 0)
    {
        if ([isOpenMsg isEqualToString:@"YES"])
        {
            [interface isOpenMsg:YES];
        }
        else if ([isOpenMsg isEqualToString:@"NO"])
        {
            [interface isOpenMsg:NO];
        }
    }
    //=================================
    //呼叫设置
    //是否自动接听
    //自动接听
    NSString *isOpenAutoAnswer = [[NSString alloc] init];
    isOpenAutoAnswer = [defaults objectForKey:@"SAVEISOPENAUTOANSWER"];
    if (isOpenAutoAnswer.length > 0)
    {
        if ([isOpenAutoAnswer isEqualToString:@"YES"])
        {
            [interface isOpenAutoAnswer:YES];
        }
        else if ([isOpenAutoAnswer isEqualToString:@"NO"])
        {
            [interface isOpenAutoAnswer:NO];
        }
    }
    //自动呼叫应答码
    NSString *isAutoAnswerCallnub = [[NSString alloc] init];
    isAutoAnswerCallnub = [defaults objectForKey:@"SAVEAUTOANSWERCALLNUMBER"];
    if (isAutoAnswerCallnub.length > 0)
    {
        if ([isAutoAnswerCallnub isEqualToString:@"183"])
        {
            [interface autoAnswerCallNumber:@"183"];
        }
        else if ([isAutoAnswerCallnub isEqualToString:@"180"])
        {
            [interface autoAnswerCallNumber:@"180"];
        }
    }
    else
    {
        [interface autoAnswerCallNumber:@"180"];
        [defaults setObject:@"180" forKey:@"SAVEAUTOANSWERCALLNUMBER"];
    }
//    //=================================
    //报警配置
    //设置报警服务器地址和端口号
//    NSString *alarmIPAddressStr = [[NSString alloc] init];
//    alarmIPAddressStr = [defaults valueForKey:@"SAVEALARMIPADDRESS"];
//    
//    NSString *alarmIPPortStr = [[NSString alloc] init];
//    alarmIPPortStr = [defaults valueForKey:@"SAVEALARMIPPORT"];
//    
//    if (alarmIPPortStr.length > 0 && alarmIPAddressStr.length > 0 )
//    {
//        [interface setAlarmIPAddressAndPort:alarmIPAddressStr andPort:alarmIPPortStr];
//    }
//    else
//    {
//        [defaults setObject:@"61.144.222.195" forKey:@"SAVEALARMIPADDRESS"];
//        [defaults setObject:@"6020" forKey:@"SAVEALARMIPPORT"];
//        [interface setAlarmIPAddressAndPort:@"61.144.222.195" andPort:@"6020"];
//    }
    
    //=================================
    //其他设置
    //基本呼叫状态
    NSString *isDisplayCallStatus = [[NSString alloc] init];
    isDisplayCallStatus = [defaults objectForKey:@"SAVEISDISPLAYCALLSTATUS"];
    if (isDisplayCallStatus.length > 0)
    {
        
    }
    else
    {
        [defaults setObject:@"NO" forKey:@"SAVEISDISPLAYCALLSTATUS"];
    }
    //=================================
    //是否在通话中的默认设置
    [defaults setObject:@"NO" forKey:@"ISINCALLSTATENOW"];
    //是否在后台时并且为UDP的情况下来电开到了前台 的默认设置
    [defaults setObject:@"NO" forKey:@"ISBACKGROUNDINCALL"];
    
    
    //是否在短信界面中
    [defaults setBool:NO forKey:@"ISINPROMPTCHATVIEW"];
    [defaults synchronize];
    
}

- (void)timerForIterator
{
//    NSLog(@"timerTest");
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    [interface iterator];
}

#pragma mark -
#pragma mark incomgingCallMethod

- (void)callincoming
{
    dispatch_async(dispatch_get_main_queue(),^{
        //设置本地通知
        UIApplication *app = [UIApplication sharedApplication];
        NSArray *oldNotifications = [app scheduledLocalNotifications];
        // Clear out the old notification before scheduling a new one.
        if (0 < [oldNotifications count])
        {
            [app cancelAllLocalNotifications];
        }
        // Create a new notification
        UILocalNotification *alarm = [[UILocalNotification alloc] init];
        if (alarm)
        {
            //来电的本地通知
            alarm.timeZone = [NSTimeZone localTimeZone];
            alarm.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
            alarm.repeatInterval = 0;
            alarm.soundName = @"complete.wav";//@"default";
            NSDate *nowDate = [NSDate date];
            NSString *nowTime = [NSDateFormatter localizedStringFromDate:nowDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterShortStyle];
            alarm.alertBody = [NSString stringWithFormat:@"%@[%@]%@\n[%@]",[SIPInterface shareSIPInterface].incomingDisplayName,[SIPInterface shareSIPInterface].incomingNumber,NSLocalizedString(@"incoming", @"来电 incoming"),nowTime];
            alarm.alertAction = NSLocalizedString(@"open", @"打开 open");
            [app scheduleLocalNotification:alarm];
        }
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        BOOL isInChatRoom = [defaults boolForKey:@"ISINPROMPTCHATVIEW"];
        if (isInChatRoom == YES)
        {
            //发送有新的即时消息通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ISINCOMINGWITHCHATROOM" object:nil];
        }
        else
        {
            //切换到来电视频界面
            IncomingViewController *incomingView = [[IncomingViewController alloc] init];
            incomingView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self.tabBarVC presentModalViewController:incomingView animated:YES];
        }
    });
}

#pragma mark -
#pragma mark XMLRPCMethod

//连接服务器
- (void)readPostMessage
{
    //查找一个可用的全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //将要做的操作放入队列
    dispatch_async(queue,^{
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *tempUserName = [[NSString alloc] init];
        tempUserName = [defaults objectForKey:@"SAVEUSERNAME"];
        BOOL tempRegisterStatus = [defaults boolForKey:@"REGISTERSTATUS"];
        //判断是否是已登录状态
        if (tempUserName.length > 0 && tempRegisterStatus == YES)
        {
            NSURL *url = [NSURL URLWithString:@"http://61.144.222.195:2154/WRTrpcService/message"];
            //创建一个连接服务器的类，和sdk里面NSURLConnection，它其实是对这个类进行了封装你可以看它源代码
            XMLRPCConnectionManager *manager = [XMLRPCConnectionManager sharedManager];
            //创建一个请求，这个类相当于sdk里面的NSURLRequest
            XMLRPCRequest *request = [[XMLRPCRequest alloc] initWithURL: url];
            //调用服务器的方法
            [request setMethod:@"messageService.GetMessage" withParameter:tempUserName];
            //设置代理回调
            [manager spawnConnectionWithXMLRPCRequest:request delegate:self];
        }
    });
}

//接收完之后发给服务器的回馈
- (void)postEndMehod:(NSArray *)array
{
    //查找一个可用的全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //将要做的操作放入队列内
    dispatch_async(queue,^{
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        
        NSString *tempUserName = [[NSString alloc] init];
        
        tempUserName = [defaults objectForKey:@"SAVEUSERNAME"];
        
        NSURL *url = [NSURL URLWithString:@"http://61.144.222.195:2154/WRTrpcService/message"];
        
        //创建一个请求，这个类相当于sdk里面的NSURLRequest
        XMLRPCRequest *request = [[XMLRPCRequest alloc] initWithURL: url];
        
        //服务器的方法要传的参数是网址和数组和用户名
        NSArray *tempArray = [NSArray arrayWithArray:array];
        NSArray *tempArray1 = [[NSArray alloc] init];
        tempArray1 = @[tempArray,tempUserName];//将两项参数放入数组中
        
        //创建服务器的类
        XMLRPCConnectionManager *manager = [XMLRPCConnectionManager sharedManager];
        
        //调用服务器的方法
        [request setMethod:@"messageService.ReceiveSuccess" withParameters:tempArray1];
        [manager spawnConnectionWithXMLRPCRequest:request delegate:self];
    });
}

//错误信息返回
-(void)request:(XMLRPCRequest *)request didFailWithError:(id)error
{
    NSLog(@"%@",error);
}

//得到服务器返回的数据
-(void) request:(XMLRPCRequest *)request didReceiveResponse:(XMLRPCResponse *)response
{
    //查找一个可用的全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //将要做的操作放入队列
    dispatch_async(queue,^{
        //打印出来看下
        NSLog(@"%@",response.object);    //这个回调会返回xml地址或者是返回success字符串
        
        if (response.object != nil)
        {
            if ([[response.object description] isEqualToString:@"success"])
            {
                
            }
            else
            {
                self.tempArray = [[NSArray alloc] init];
                self.tempArray = (NSArray *)response.object;  //获取XML网址
                [self reloadView:self.tempArray];             //解析XML网址的内容
            }
        }
    });
}
-(BOOL) request:(XMLRPCRequest *)request canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return YES;
}

-(void) request:(XMLRPCRequest *)request didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    
}
-(void) request:(XMLRPCRequest *)request didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge
{
    
}

#pragma mark -
#pragma mark hppleMethod
//解析xml操作 利用HPPLE进行XML的解析
- (void)reloadView:(NSArray *)array
{
    //查找一个可用的全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //将要做的操作放入队列
    dispatch_async(queue,^{
        for (NSString *urlStr in array)
        {
            __block NSString *tempTime = [[NSString alloc] init];  //用于存时间
            __block NSString *tempKind = [[NSString alloc] init];  //用于存种类
            __block NSString *tempPostKind = [[NSString alloc] init];   //用于存推送种类
            __block NSString *tempURL = [[NSString alloc] init];   //用于存解析出来的地址
            __block NSString *tempText = [[NSString alloc] init];  //用于存解析出来的文本
            
            
            NSURL *url = [NSURL URLWithString:urlStr];
            NSData *xmlData = [NSData dataWithContentsOfURL:url];
            //创建一个HPPLE解析器
            TFHpple *htmlHppple=[TFHpple hppleWithXMLData:xmlData];
            
            //创建并发队列组
            dispatch_group_t group = dispatch_group_create();
            
            //分别放入并发队列
            //并发队列是分别将几段函数块同时进行，等待全部完成后继续下一步
            //因为xml分为六种形式，所以分六个队列来进行判断xml内容是哪一个类型
            dispatch_group_async(group, queue, ^{
                NSArray *titleArray1 = [htmlHppple searchWithXPathQuery:@"//message[@type = 'notice']/picture"];
                for(int i = 0; i < titleArray1.count; i++)
                {
                    TFHppleElement *t = titleArray1[i];
                    
                    if ([t text].length > 0)
                    {
                        tempText = [t text];
                    }
                    else
                    {
                        tempText = @"";
                    }
                    
                    NSDictionary *elementContent = [t attributes];
                    tempURL = [elementContent objectForKey:@"src"];
                    
                    tempKind = @"picture";
                    tempPostKind = @"notice";
                    
                }
            });
            
            
            //分别放入并发队列
            dispatch_group_async(group, queue, ^{
                
                NSArray *titleArray2 = [htmlHppple searchWithXPathQuery:@"//message[@type = 'notice']/text"];
                for(int i = 0; i < titleArray2.count; i++)
                {
                    TFHppleElement *t = titleArray2[i];
                    if ([t text].length > 0)
                    {
                        tempText = [t text];
                    }
                    else
                    {
                        tempText = @"";
                    }
                    
                    tempKind = @"text";
                    tempPostKind = @"notice";
                    tempURL = @"NULL";
                    
                }
            });
            
            //分别放入并发队列
            dispatch_group_async(group, queue, ^{
                NSArray *titleArray3 = [htmlHppple searchWithXPathQuery:@"//message[@type = 'notice']/video"];
                for(int i = 0; i < titleArray3.count; i++)
                {
                    TFHppleElement *t = titleArray3[i];
                    if ([t text].length > 0)
                    {
                        tempText = [t text];
                    }
                    else
                    {
                        tempText = @"";
                    }
                    NSDictionary *elementContent = [t attributes];
                    tempURL = [elementContent objectForKey:@"src"];
                    
                    tempKind = @"video";
                    tempPostKind = @"notice";
                }
            });
            
            //分别放入并发队列
            dispatch_group_async(group, queue, ^{
                NSArray *titleArray4 = [htmlHppple searchWithXPathQuery:@"//message[@type = 'advert']/picture"];
                for(int i = 0; i < titleArray4.count; i++)
                {
                    TFHppleElement *t = titleArray4[i];
                    if ([t text].length > 0)
                    {
                        tempText = [t text];
                    }
                    else
                    {
                        tempText = @"";
                    }
                    NSDictionary *elementContent = [t attributes];
                    tempURL = [elementContent objectForKey:@"src"];
                    
                    tempKind = @"picture";
                    tempPostKind = @"advert";
                }
            });
            
            //分别放入并发队列
            dispatch_group_async(group, queue, ^{
                NSArray *titleArray5 = [htmlHppple searchWithXPathQuery:@"//message[@type = 'advert']/video"];
                for(int i = 0; i < titleArray5.count; i++)
                {
                    TFHppleElement *t = titleArray5[i];
                    if ([t text].length > 0)
                    {
                        tempText = [t text];
                    }
                    else
                    {
                        tempText = @"";
                    }
                    NSDictionary *elementContent = [t attributes];
                    tempURL = [elementContent objectForKey:@"src"];
                    
                    tempKind = @"video";
                    tempPostKind = @"advert";
                }
            });
            
            //分别放入并发队列
            dispatch_group_async(group, queue, ^{
                NSArray *titleArray6 = [htmlHppple searchWithXPathQuery:@"//message[@type = 'advert']/text"];
                for(int i = 0; i < titleArray6.count; i++)
                {
                    TFHppleElement *t = titleArray6[i];
                    if ([t text].length > 0)
                    {
                        tempText = [t text];
                    }
                    else
                    {
                        tempText = @"";
                    }
                    
                    tempKind = @"text";
                    tempPostKind = @"advert";
                }
            });
            
            //分别放入并发队列
            dispatch_group_async(group, queue, ^{
                NSArray *titleArray7 = [htmlHppple searchWithXPathQuery:@"//message"];
                for (int i = 0; i < titleArray7.count; i++)
                {
                    TFHppleElement *t = titleArray7[i];
                    NSDictionary *elementContent = [t attributes];
                    NSNumber *value = [[NSNumber alloc] init];
                    value = [elementContent objectForKey:@"time"];
                    long long valuell = [value longLongValue]/1000;
                    NSNumber *longValueTime = [NSNumber numberWithLongLong:valuell];
                    NSTimeInterval nsTimeInterval = [longValueTime longValue];
                    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:nsTimeInterval];
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    tempTime = [dateFormatter stringFromDate:date];
                }
            });
            
            //等待所有并发队列完成
            dispatch_group_wait(group,DISPATCH_TIME_FOREVER);
            //如果文本字段大于0或者存在url连接 则说明有消息推送了过来
            if (tempText.length > 0 | tempURL.length > 0)
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //让信息的tabbarItem上面显示“new”
                    self.navForMsg.tabBarItem.badgeValue = @"new";
                });
                
                //发出短信的声音
                SoundEngine *sound = [SoundEngine shareSound];
                [sound returnSetCategory];
                [sound PlayMessageTone];
                
                //写进数据库
                [self savePostMsg:tempTime andKind:tempKind andNotice:tempPostKind andPath:tempURL andText:tempText];
            }
        }
        if (array.count > 0)
        {
            [self postEndMehod:array];
        }
    });
}
//将解析出来的数据保存到数据库的操作
- (void)savePostMsg:(NSString *)time andKind:(NSString *)kind andNotice:(NSString *)notice andPath:(NSString *)path andText:(NSString *)text
{
    
    PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
    [postMsgDB savePostMsg:time andKind:kind andNotice:notice andPath:path andText:text];
    
    //若执行该方法，说明有新的数据，这个时候发送一条本地通知
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *oldNotifications = [app scheduledLocalNotifications];
    if (0 < [oldNotifications count])
    {
        [app cancelAllLocalNotifications];
    }
    // Create a new notification
    UILocalNotification *alarm = [[UILocalNotification alloc] init];
    if (alarm)
    {
        alarm.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
        alarm.timeZone = [NSTimeZone localTimeZone];
        alarm.repeatInterval = 0;
        alarm.soundName = @"complete.wav";//@"default";
        NSDate *nowDate = [NSDate date];
        NSString *nowTime = [NSDateFormatter localizedStringFromDate:nowDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterShortStyle];
        alarm.alertBody = [NSString stringWithFormat:@"%@\n[%@]",NSLocalizedString(@"have A Push Message", @"有一条推送信息 have a push message"),nowTime];
        alarm.alertAction = NSLocalizedString(@"open", @"打开 open");
        [app scheduleLocalNotification:alarm];
    }
    
    //发送有新的推送消息通知，让其在推送消息的cell上显示new
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HAVEANEWPOSTMSG" object:nil];
    
    PostMessage *postMsg = [[PostMessage alloc] init];
    postMsg.time = time;
    postMsg.status = @"未读";
    postMsg.notice = notice;
    postMsg.path = path;
    postMsg.text = text;
    postMsg.kind = kind;
    
    //发送有新的推送消息通知，刷新tableview
    [[NSNotificationCenter defaultCenter] postNotificationName:@"RELOADTABLEVIEWPOSTMSG" object:postMsg];
    
}

#pragma mark -
#pragma mark tabbarControllerDlegateMethod
//用于监听tabbarController的选择
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    //判断若信息栏上有“new”，点击后让其消失
    if (tabBarController.selectedIndex == 1)
    {
        if (self.navForMsg.tabBarItem.badgeValue.length > 0)
        {
            self.navForMsg.tabBarItem.badgeValue = nil;
        }
    }
//    CATransition* animation = [CATransition animation];
//    [animation setDuration:0.8f];
//    [animation setType:@"rippleEffect"];
//    //        [animation setSubtype:kCATransitionFromBottom];
//    //        [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
//    [[self.tabBarVC.view layer] addAnimation:animation forKey:@"switchView"];
}

#pragma mark -
#pragma mark reachabilityMethod
//接收到通知传过来的网络状态变化
- (void)reachabilityChanged:(NSNotification *)note
{
	Reachability* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
	[self updateInterfaceWithReachability:curReach];
}
//对应的变化做处理
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
	if (reachability == self.internetReachability)
	{
		NetworkStatus netStatus = [reachability currentReachabilityStatus];
        BOOL connectionRequired = [reachability connectionRequired];
        
        switch (netStatus)
        {
            case NotReachable:
            {
                NSLog(@"没有网络");
                connectionRequired = NO;
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setBool:NO forKey:@"ISREACHABILITY"];
                [defaults synchronize];
                break;
            }
                
            case ReachableViaWWAN:
            {
                NSLog(@"WWAN");
                connectionRequired = YES;
                break;
            }
            case ReachableViaWiFi:
            {
                NSLog(@"WIFI");
                connectionRequired = YES;
                break;
            }
        }
        
        if (connectionRequired)
        {
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setBool:YES forKey:@"ISREACHABILITY"];
            [defaults synchronize];
            NSLog(@"连接上的哦");
        }
    }
}

#pragma mark -
#pragma mark tabbarHaveNewMethod
//当有好友消息时
- (void)setTabBarHaveNew:(NSNotification *)notification
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue,^{
        //发出短信的声音
        SoundEngine *sound = [SoundEngine shareSound];
        [sound returnSetCategory];
        [sound PlayMessageTone];
        
        dispatch_async(dispatch_get_main_queue(),^{
            
            FriendRespondMessage *frdRspdMsg = [[FriendRespondMessage alloc] init];
            frdRspdMsg = (FriendRespondMessage *)notification.object;
            
            //让信息的tabbarItem上面显示“new”
            self.navForMsg.tabBarItem.badgeValue = @"new";
            
            //发送有新的推送消息通知，让其在推送消息的cell上显示new
            [[NSNotificationCenter defaultCenter] postNotificationName:@"HAVEFRIENDREQUESTMSG" object:nil];
            
            UIApplication *app = [UIApplication sharedApplication];
            NSArray *oldNotifications = [app scheduledLocalNotifications];
            if (0 < [oldNotifications count])
            {
                [app cancelAllLocalNotifications];
            }
            UILocalNotification *alarm = [[UILocalNotification alloc] init];
            if (alarm)
            {
                alarm.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
                alarm.timeZone = [NSTimeZone localTimeZone];
                alarm.repeatInterval = 0;
                alarm.soundName = @"complete.wav";//@"default";
                NSDate *nowDate = [NSDate date];
                NSString *nowTime = [NSDateFormatter localizedStringFromDate:nowDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterShortStyle];
                if (frdRspdMsg.status == 0)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@%@[%@]%@\n[%@]",NSLocalizedString(@"add", @"添加 add"),frdRspdMsg.disPlayName,frdRspdMsg.userName,NSLocalizedString(@"failure", @"失败 failure"),nowTime];
                }
                else if (frdRspdMsg.status == 1 || frdRspdMsg.status == 2 || frdRspdMsg.status == 6 || frdRspdMsg.status == 7)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@[%@]%@\n[%@]",frdRspdMsg.disPlayName,frdRspdMsg.userName,NSLocalizedString(@"agreed To Add Friend", @"同意添加您为好友 Agreed to add you as a friend"),nowTime];
                }
                else if (frdRspdMsg.status == 11)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@[%@]%@\n[%@]",frdRspdMsg.disPlayName,frdRspdMsg.userName,NSLocalizedString(@"refused To Add Friend", @"拒绝添加您为好友 Refused to add you as a friend"),nowTime];
                }
                else if (frdRspdMsg.status == 12)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@[%@]%@\n[%@]",frdRspdMsg.disPlayName,frdRspdMsg.userName,NSLocalizedString(@"request To Add Friend", @"请求添加您为好友 The request to add you as a friend"),nowTime];
                }
                alarm.alertAction = NSLocalizedString(@"open", @"打开 open");
                [app scheduleLocalNotification:alarm];
            }
        });
    });
}
//当有即时消息时
- (void)setTabBarHaveChat:(NSNotification *)notification
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue,^{
        //发出短信的声音
        SoundEngine *sound = [SoundEngine shareSound];
        [sound returnSetCategory];
        [sound PlayMessageTone];
        
        dispatch_async(dispatch_get_main_queue(),^{
            
            PromptChatMessage *promptChatMsg = [[PromptChatMessage alloc] init];
            promptChatMsg = (PromptChatMessage *)notification.object;
            
            //让信息的tabbarItem上面显示“new”
            self.navForMsg.tabBarItem.badgeValue = @"new";
            
            //发送有新的推送消息通知，让其在刷新对应的cell
            [[NSNotificationCenter defaultCenter] postNotificationName:@"HAVEANEWONLINEMSG" object:nil];
            
            UIApplication *app = [UIApplication sharedApplication];
            NSArray *oldNotifications = [app scheduledLocalNotifications];
            if (0 < [oldNotifications count])
            {
                [app cancelAllLocalNotifications];
            }
            UILocalNotification *alarm = [[UILocalNotification alloc] init];
            if (alarm)
            {
                alarm.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
                alarm.timeZone = [NSTimeZone localTimeZone];
                alarm.repeatInterval = 0;
                alarm.soundName = @"complete.wav";//@"default";
                
                NSString *tempMarkName = [[NSString alloc] init];
                ContactsDateBase *contactDB = [ContactsDateBase shareContactsDataBase];
                for (int i = 0 ;i < contactDB.userNameArray.count ; i ++)
                {
                    if ([promptChatMsg.userName isEqualToString:contactDB.userNameArray[i]] && [promptChatMsg.ipPort isEqualToString:contactDB.ipPortArray[i]])
                    {
                        tempMarkName = contactDB.markNameArray[i];
                        break;
                    }
                }
                if (tempMarkName.length > 0)
                {
                    
                }
                else
                {
                    tempMarkName = promptChatMsg.userName;
                }
                
                if ([promptChatMsg.isTextOrImg isEqualToString:@"Image"])
                {
                    
                    alarm.alertBody = [NSString stringWithFormat:@"%@\n%@:[%@]",NSLocalizedString(@"You Have An Instant Message", @"您有一条即时信息 You have an instant message"),tempMarkName,NSLocalizedString(@"Image", @"图片 Image")];
                }
                else
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@\n%@:%@",NSLocalizedString(@"You Have An Instant Message", @"您有一条即时信息 You have an instant message"),tempMarkName,promptChatMsg.content];
                }
                alarm.alertAction = NSLocalizedString(@"open", @"打开 open");
                [app scheduleLocalNotification:alarm];
            }
        });
    }); 
}
- (void)setTabBarHaveAlarm:(NSNotification *)notification
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue,^{
        //发出短信的声音
        SoundEngine *sound = [SoundEngine shareSound];
        [sound returnSetCategory];
        [sound PlayMessageTone];
        
        dispatch_async(dispatch_get_main_queue(),^{
            
            AlarmMessage *alarmMsg = [[AlarmMessage alloc] init];
            alarmMsg = (AlarmMessage *)notification.object;
            
            //让信息的tabbarItem上面显示“new”
            self.navForMsg.tabBarItem.badgeValue = @"new";
            
            //发送有新的推送消息通知，让其在推送消息的cell上显示new
            [[NSNotificationCenter defaultCenter] postNotificationName:@"HAVENEWALARMMSG" object:nil];
            
            UIApplication *app = [UIApplication sharedApplication];
            NSArray *oldNotifications = [app scheduledLocalNotifications];
            if (0 < [oldNotifications count])
            {
                [app cancelAllLocalNotifications];
            }
            UILocalNotification *alarm = [[UILocalNotification alloc] init];
            if (alarm)
            {
                alarm.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
                alarm.timeZone = [NSTimeZone localTimeZone];
                alarm.repeatInterval = 0;
                alarm.soundName = @"complete.wav";//@"default";
                NSDate *nowDate = [NSDate date];
                NSString *nowTime = [NSDateFormatter localizedStringFromDate:nowDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterShortStyle];
                if (alarmMsg.alarmType == 1)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"fire", @"火灾 Fire"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 2)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"gas", @"瓦斯 Gas"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 3)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"infrared", @"红外线 Infrared"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 4)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"magnetic", @"门磁 Magnetic"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 5)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"zone5", @"防区5 Zone 5"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 6)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"zone6", @"防区6 Zone 6"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 7)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"zone7", @"防区7 Zone 7"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 8)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"zone8", @"防区8 Zone 8"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 9)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"tamper", @"防拆 Tamper"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 10)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"illegaldoor", @"非法开门 Illegal door"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 11)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"stressdoor", @"胁迫开门 Stress door"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 12)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"hostMagnetic", @"主机门磁 Host Magnetic"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 13)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"undervoltage", @"欠压 Undervoltage"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 14)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@\n[%@]",NSLocalizedString(@"voltage returns to normal", @"电压恢复正常 Voltage returns to normal"),nowTime];
                }
                else if (alarmMsg.alarmType == 15)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"arming", @"布防 Arming"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 16)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"disarming", @"撤防 Disarming"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 17)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"batch", @"批处理 Batch"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                else if (alarmMsg.alarmType == 18)
                {
                    alarm.alertBody = [NSString stringWithFormat:@"%@ %@\n[%@]",NSLocalizedString(@"urgent", @"紧急 Urgent"),NSLocalizedString(@"alarm", @"报警 Alarm"),nowTime];
                }
                alarm.alertAction = NSLocalizedString(@"open", @"打开 open");
                [app scheduleLocalNotification:alarm];
            }
        });
    });
}

//沙盒文件路径  videoCode.plist 和 videoOrder.plist 和 audioCode.plist 和 audioOrder.plist
- (NSString *)dataFilePath:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:fileName];
}

//后台检测网络需要
- (void)setupNetworkReachabilityCallback {
	SCNetworkReachabilityContext *ctx=NULL;
    //any internet cnx
	struct sockaddr_in zeroAddress;
	bzero(&zeroAddress, sizeof(zeroAddress));
	zeroAddress.sin_len = sizeof(zeroAddress);
	zeroAddress.sin_family = AF_INET;
	
    if (proxyReachability)
    {
        SCNetworkReachabilityUnscheduleFromRunLoop(proxyReachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
        CFRelease(proxyReachability);
        proxyReachability = nil;
    }
    
    proxyReachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
    
	if (!SCNetworkReachabilitySetCallback(proxyReachability, (SCNetworkReachabilityCallBack)networkReachabilityCallBack, ctx))
    {
        NSLog(@"Cannot register reachability cb: %s",SCErrorString(SCError()));
		return;
	}
	if(!SCNetworkReachabilityScheduleWithRunLoop(proxyReachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
    {
        NSLog(@"Cannot register schedule reachability cb: %s",SCErrorString(SCError()));
		return;
	}
	// this check is to know network connectivity right now without waiting for a change. Don'nt remove it unless you have good reason. Jehan
	SCNetworkReachabilityFlags flags;
	if (SCNetworkReachabilityGetFlags(proxyReachability, &flags))
    {
		networkReachabilityCallBack(proxyReachability,flags,nil);
	}
}

void networkReachabilityCallBack(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* nilCtx)
{
	SCNetworkReachabilityFlags networkDownFlags=kSCNetworkReachabilityFlagsConnectionRequired |kSCNetworkReachabilityFlagsConnectionOnTraffic | kSCNetworkReachabilityFlagsConnectionOnDemand;
    
	
        
        struct NetworkReachabilityContext *ctx = nilCtx ? ((struct NetworkReachabilityContext*)nilCtx) : 0;
		if ((flags == 0) || (flags & networkDownFlags))
        {
			AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
			app.connectivity = none;
			[app kickOffNetworkConnection];
		} else {
			Connectivity  newConnectivity;
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
//			BOOL isWifiOnly = lp_config_get_int(linphone_core_get_config(theLinphoneCore), LINPHONERC_APPLICATION_KEY, "wifi_only_preference",FALSE);
            if (!ctx)
                newConnectivity = flags & kSCNetworkReachabilityFlagsIsWWAN ? wwan:wifi;
            else
                newConnectivity = wifi;
            
			if (newConnectivity == wwan
				
				&& (app.connectivity == newConnectivity || app.connectivity == none))
            {
//				linphone_proxy_config_expires(proxy, 0);
			}
			
			if (app.connectivity != newConnectivity)
            {
				// connectivity has changed
//				linphone_core_set_network_reachable(theLinphoneCore,false);
				if (newConnectivity == wwan)
                {
//					linphone_proxy_config_expires(proxy, 0);
				}
//				linphone_core_set_network_reachable(theLinphoneCore,true);
//				[LinphoneLogger logc:LinphoneLoggerLog format:"Network connectivity changed to type [%s]",(newConnectivity==wifi?"wifi":"wwan")];
				[app waitForRegisterToArrive];
			}
			app.connectivity=newConnectivity;
		}
		if (ctx && ctx->networkStateChanged)
        {
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            (*ctx->networkStateChanged)(app.connectivity);
        }
}

- (void)kickOffNetworkConnection {
	/*start a new thread to avoid blocking the main ui in case of peer host failure*/
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.200"/*"linphone.org"*/, 15000, nil, &writeStream);
        CFWriteStreamOpen (writeStream);
        const char* buff="hello";
        CFWriteStreamWrite (writeStream,(const UInt8*)buff,strlen(buff));
        CFWriteStreamClose (writeStream);
        CFRelease(writeStream);
    });
}

- (void)waitForRegisterToArrive{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]
		&& [UIApplication sharedApplication].applicationState ==  UIApplicationStateBackground)
    {
        stopWaitingRegisters = FALSE;
        NSLog(@"Starting long running task for registering");
        UIBackgroundTaskIdentifier bgid = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler: ^{
            stopWaitingRegisters=TRUE;
            NSLog(@"Starting long running task for registering");
        }];
        for(int i=0;i<100 && (!stopWaitingRegisters);i++){
            SIPInterface *interface = [SIPInterface shareSIPInterface];
            [interface iterator];
            usleep(20000);
        }
        NSLog(@"Ending long running task for registering");
        [[UIApplication sharedApplication] endBackgroundTask:bgid];
    }
}

//-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
//{
//    BOOL isInBackground = NO;
//    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
//    {
//        isInBackground = YES;
//    }
//    if (isInBackground)
//    {
//        [self sendBackgroundLocationToServer:@"dxs"];
//    }
//    else
//    {
//        // ...
//    }
//}
-(void) sendBackgroundLocationToServer:(NSString *)location
{
    
    __block UIBackgroundTaskIdentifier
        bgTask = [[UIApplication sharedApplication]
       beginBackgroundTaskWithExpirationHandler:
         ^{
                 [[UIApplication sharedApplication] endBackgroundTask:bgTask];
             
             
         }];
       counter++;
       NSLog(@"counter －> %d",counter);
   
       if (bgTask != UIBackgroundTaskInvalid)
       {
                        [[UIApplication sharedApplication] endBackgroundTask:bgTask];
                         bgTask = UIBackgroundTaskInvalid;
        }
}

- (void)dealloc
{
    //取消通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"INCOMINGCALL" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"FRIENDREQUSTFORTABBAR" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PROMPTCHATTABBAR" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ALARMTABBAR" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
    [self.postTimer invalidate];
    self.postTimer = nil;
}

@end
